package com.base.cn.platform.os.controller.web.user.center.cash;

import com.base.cn.platform.os.common.WebBaseController;
import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.j2cache.J2CacheRegion;
import com.base.cn.platform.os.common.md5.MD5;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.web.thirdLogin.WXLoginUtils;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.manage.user.account.CusUserCashAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 用户提现账户Controller
 *
 * @author s.li
 * @date 2018/12/01
 */
@Controller
public class WebCusUserCashAccountController extends WebBaseController {

    @Autowired
    private CusUserCashAccountService cusUserCashAccountService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private CustomCacheChannel customCacheChannel;

    /**
     * 我的提现
     * @return 操作页面
     */
    @RequestMapping("/web/uc/account/myCash")
    public String ucMyCash() {

        return resultPage("/user/center/myAccount/cash/u-myCash");
    }

    /**
     * 获取用户提现账户数据列表
     * @param request HttpServletRequest
     * @param model Model
     * @return 数据页面
     */
    @RequestMapping("/web/uc/account/findUserCashAccount")
    public String findUserCashAccount(HttpServletRequest request,Model model){
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        TreeMap<Integer,Map<String,Object>> userCashAccountMap = cusUserCashAccountService.findUserCashAccount(userId);
        if(ObjectUtils.isEmpty(userCashAccountMap)){
            userCashAccountMap = new TreeMap<>();
        }
        model.addAttribute("userCashAccountMap",userCashAccountMap);
        return resultPage("/user/center/myAccount/cash/user-cash-account");
    }

    /**
     * 获取用户绑定的账户列表
     * @param request
     * @return Map<String,Object>
     */
    @RequestMapping("/web/uc/account/findUserCashAccountList")
    @ResponseBody
    public Map<String,Object> findUserCashAccountList(HttpServletRequest request){
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        List<Map<String,Object>> cashAccountList = cusUserCashAccountService.findUserCashAccountList(userId);
        return ResultUtil.SUCCESS(cashAccountList);
    }

    /**
     * 通过账户类型，查询提现账户
     * @param request HttpServletRequest
     * @param accountType 账户类型
     * @return Map<String,Object>
     */
    @RequestMapping("/web/uc/account/findUserCashAccountByType")
    @ResponseBody
    public Map<String,Object> findUserCashAccountByType(HttpServletRequest request,
                                                        @RequestParam("accountType") int accountType){
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String,Object> userCashAccount = cusUserCashAccountService.findUserCashAccountByType(userId,accountType);
        return ResultUtil.SUCCESS(userCashAccount);
    }

    /**
     * 保存绑定的支付宝账户
     * @param realName 账户真实姓名
     * @param account 支付账号
     * @return Map<String,Object>
     */
    @RequestMapping("/web/uc/account/saveZfbCashAccount")
    @ResponseBody
    public Map<String,Object> saveZfbCashAccount(HttpServletRequest request,
                                                 @RequestParam("realName")String realName ,
                                                 @RequestParam("account") String account){
        Map<String,Object> params = new HashMap<>();
        params.put("accountType",1);
        params.put("realName",realName);
        params.put("account",account);
        params.put("userId",webMobileLoginUtil.getLoginUserId(request));
        return cusUserCashAccountService.saveUserCashAccount(params);
    }

    //============================================================================================
    /**
     * 初始化绑定微信
     * @param request HttpServletRequest
     * @param realName
     * @return Map<String,Object>
     */
    @RequestMapping("/web/uc/account/bindingWeiXin")
    @ResponseBody
    public Map<String,Object> bindingWeiXin(HttpServletRequest request,
                                            @RequestParam("realName") String realName){
        if(StringUtils.isEmpty(realName)){
            return ResultUtil.ERROR("请填写提现微信账户的真实姓名");
        }
        String contextPath = request.getRequestURL().toString().split(request.getRequestURI())[0];
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        String signVal = userId +"_" +realName;
        String key = MD5.getMD5(signVal)+"web";
        customCacheChannel.set(J2CacheRegion.THIRTY_DAY_REGION.getKey(), key, signVal);
        String callBack = contextPath + "/web/account/getWeiXinCode?sign="+key;
        logger.info("==========================callBack:"+callBack);
        Map<String,Object> resultMap =ResultUtil.SUCCESS("验证成功",callBack);
        resultMap.put("verificationKey",key+"verification");
        return resultMap;
    }

    /**
     * 获取微信Code
     * @param request
     * @param sign 签名
     * @return 操作页面
     * @throws Exception
     */
    @RequestMapping("/web/account/getWeiXinCode")
    public String getWeiXinCode(HttpServletRequest request,@RequestParam("sign") String sign) throws  Exception{
        TreeMap<String,String> wxConfigMap = sysConfigService.getSysConfigContext(ConfigName.WXLOGIN);
        String appId= wxConfigMap.get("appId");//开放平台网页Admin应用AppId;
        String contextPath = request.getRequestURL().toString().split(request.getRequestURI())[0];
        String redirect_uri = contextPath + "/web/account/weiXinRedirect";
        //重定向到微信网页授权登录
        StringBuilder callBack = new StringBuilder("https://open.weixin.qq.com/connect/oauth2/authorize?appid=");
        callBack.append(appId).append("&redirect_uri=").append(URLEncoder.encode(redirect_uri, "utf-8"));
        callBack.append("&response_type=code&scope=snsapi_userinfo&state=");
        logger.info("=======================sign:"+sign);
        callBack.append(sign);
        callBack.append("#wechat_redirect");
        return redirect(request,callBack.toString());
    }

    /**
     * 获取微信Code的回调
     * @param request
     * @param model
     * @return 返回提示页面
     * @throws Exception
     */
    @RequestMapping("/web/account/weiXinRedirect")
    public String weiXinRedirect(HttpServletRequest request,
                                 Model model) throws Exception{
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        logger.info("===================code:"+code);
        logger.info("===================state:"+state);
        String stateVal = (String)customCacheChannel.get(J2CacheRegion.THIRTY_DAY_REGION.getKey(), state).getValue();
        String message = "系统错误";
        if(StringUtils.isNotEmpty(stateVal)){
            String[] arr = stateVal.split("_");
            BigDecimal userId = new BigDecimal(arr[0]);//用户ID
            String realName = arr[1];//账户真实姓名
            TreeMap<String,String> wxConfigMap = sysConfigService.getSysConfigContext(ConfigName.WXLOGIN);
            String appId = wxConfigMap.get("appId");//微信开放平台PC应用appId
            String appSecret= wxConfigMap.get("appSecret");// 微信开放平台PC应用secret
            //微信的openId和accessToken
            Map<String,String> map = WXLoginUtils.getAccessTokenAndOpendId(appId,appSecret,code);
            String openId = map.get("openId");
            String accessToken = map.get("accessToken");
            logger.info("===================openId:"+openId);
            logger.info("===================accessToken:"+accessToken);
            Map<String,Object> params = new HashMap<>();
            params.put("accountType",2);
            params.put("realName",realName);
            params.put("account",openId);
            params.put("userId",userId);
            Map<String,Object> resultMap = cusUserCashAccountService.saveUserCashAccount(params);
            message = ResultUtil.getMessage(resultMap);
            if(ResultUtil.getSuccess(resultMap)){
                customCacheChannel.set(J2CacheRegion.ONE_MINUTE_REGION.getKey(),state+"verification",true);
            }
        }
        model.addAttribute("message",message);
        return resultPage("/user/center/myAccount/cash/wx-callback-message");
    }

    /**
     * 验证微信是否绑定成功
     * @return
     */
    @RequestMapping("/web/uc/account/verifyWeChatBindingStatus")
    @ResponseBody
    public Map<String,Object> verifyWeChatBindingStatus(@RequestParam("verificationKey") String verificationKey){
        Boolean status = (Boolean)customCacheChannel.get(J2CacheRegion.ONE_MINUTE_REGION.getKey(),verificationKey).getValue();
        if(status==null){
            return ResultUtil.ERROR();
        }
        return ResultUtil.SUCCESS();
    }
}
